// M3U8 Crawler 弹出界面脚本

// DOM元素引用
const scanBtn = document.getElementById('scan-btn');
const clearBtn = document.getElementById('clear-btn');
const searchInput = document.getElementById('search-input');
const resultsList = document.getElementById('results-list');
const status = document.getElementById('status');

// 加载时初始化
window.addEventListener('DOMContentLoaded', () => {
  // 获取并显示M3U8文件列表
  loadM3U8Files();
  
  // 添加事件监听器
  scanBtn.addEventListener('click', handleScan);
  clearBtn.addEventListener('click', handleClear);
  searchInput.addEventListener('input', handleSearch);
});

// 加载M3U8文件列表
function loadM3U8Files() {
  chrome.runtime.sendMessage({ type: 'GET_M3U8_FILES' }, (response) => {
    if (response && response.m3u8Files) {
      displayM3U8Files(response.m3u8Files);
    } else {
      status.textContent = '未检测到M3U8文件';
    }
  });
}

// 显示M3U8文件列表
function displayM3U8Files(files) {
  // 清空现有列表
  resultsList.innerHTML = '';
  
  if (files.length === 0) {
    status.textContent = '未检测到M3U8文件';
    return;
  }
  
  status.textContent = `共检测到 ${files.length} 个M3U8文件`;
  
  // 创建并添加每个文件项
  files.forEach(file => {
    const item = document.createElement('div');
    item.className = 'm3u8-item';
    
    // 格式化时间
    const formattedTime = new Date(file.timestamp).toLocaleString('zh-CN');
    
    item.innerHTML = `
      <div class="m3u8-info">
        <div class="m3u8-url">${truncateUrl(file.url)}</div>
        <div class="m3u8-time">${formattedTime}</div>
      </div>
      <div class="m3u8-actions">
        <button class="action-btn copy-btn" data-url="${file.url}">复制URL</button>
        <button class="action-btn save-btn" data-url="${file.url}">保存</button>
      </div>
    `;
    
    resultsList.appendChild(item);
  });
  
  // 为新添加的按钮添加事件监听器
  addActionButtonListeners();
}

// 添加操作按钮的事件监听器
function addActionButtonListeners() {
  // 复制URL按钮
  document.querySelectorAll('.copy-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const url = e.currentTarget.getAttribute('data-url');
      copyToClipboard(url);
    });
  });
  
  // 保存按钮
  document.querySelectorAll('.save-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const url = e.currentTarget.getAttribute('data-url');
      saveM3U8(url);
    });
  });
}

// 处理重新扫描
function handleScan() {
  status.textContent = '正在重新扫描...';
  
  // 获取当前活动标签页
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      // 向content script发送消息，触发重新扫描
      chrome.tabs.sendMessage(tabs[0].id, { type: 'REFRESH_SCAN' }, () => {
        // 重新加载列表
        setTimeout(loadM3U8Files, 1000);
      });
    }
  });
}

// 处理清空列表
function handleClear() {
  if (confirm('确定要清空所有检测到的M3U8文件吗？')) {
    chrome.runtime.sendMessage({ type: 'CLEAR_M3U8_FILES' }, (response) => {
      if (response && response.success) {
        status.textContent = '列表已清空';
        resultsList.innerHTML = '';
      }
    });
  }
}

// 处理搜索
function handleSearch() {
  const searchTerm = searchInput.value.toLowerCase();
  const items = document.querySelectorAll('.m3u8-item');
  let visibleCount = 0;
  
  items.forEach(item => {
    const urlElement = item.querySelector('.m3u8-url');
    const url = urlElement.textContent.toLowerCase();
    
    if (url.includes(searchTerm)) {
      item.style.display = 'flex';
      visibleCount++;
    } else {
      item.style.display = 'none';
    }
  });
  
  // 更新状态信息
  status.textContent = `显示 ${visibleCount} 个结果（共 ${items.length} 个）`;
}

// 复制到剪贴板
function copyToClipboard(text) {
  navigator.clipboard.writeText(text)
    .then(() => {
      showNotification('URL已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败:', err);
      showNotification('复制失败，请手动复制', true);
    });
}

// 保存M3U8文件
function saveM3U8(url) {
  status.textContent = '正在处理，请稍候...';
  
  chrome.runtime.sendMessage(
    { type: 'SAVE_M3U8', url: url },
    (response) => {
      if (response && response.success) {
        status.textContent = '保存成功';
      } else {
        status.textContent = `保存失败: ${response ? response.error : '未知错误'}`;
      }
    }
  );
}

// 显示通知
function showNotification(message, isError = false) {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `notification ${isError ? 'error' : 'success'}`;
  notification.textContent = message;
  
  // 添加到页面
  document.body.appendChild(notification);
  
  // 自动移除通知
  setTimeout(() => {
    notification.classList.add('fade-out');
    setTimeout(() => {
      document.body.removeChild(notification);
    }, 300);
  }, 2000);
}

// 截断URL以适应显示
function truncateUrl(url, maxLength = 60) {
  if (url.length <= maxLength) return url;
  return url.substring(0, maxLength / 2) + '...' + url.substring(url.length - maxLength / 2);
}